#include "customitemdelegate.h"
#include <QDebug>
#include "data.h"
#include <QLineEdit>
#include <QDateEdit>
#include <QTimeEdit>
#include <QDateTimeEdit>

customItemDelegate::customItemDelegate(QObject* parent,CustomModel *model): QStyledItemDelegate(parent),itemButton1(new ItemButton("close2"))
{
    m_CustomModel=model;
   // connect(this,&customItemDelegate::sig_btnClicked,this,&customItemDelegate::slots_btnClicked);
}

void customItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    QStyleOptionViewItem viewOption(option);
    initStyleOption(&viewOption, index);
    if (option.state.testFlag(QStyle::State_HasFocus)){
        viewOption.state = viewOption.state ^ QStyle::State_HasFocus;
    }

    if(index.isValid()!=false&&m_CustomModel!=nullptr){
        _DATA_STRUCT data=m_CustomModel->fun_GetDataItem(index);
        if(index.column()==m_CustomModel->m_btnColumn){
            itemButton1->paintButton(painter, option, mousePos);
        }
    }
    //主要靠painter指针记录来实现绘制按钮和其他控件
    QStyledItemDelegate::paint(painter, viewOption, index);
}

QSize customItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    if(index.column()==m_CustomModel->m_btnColumn){
        return option.rect.size();
    }
    return QStyledItemDelegate::sizeHint(option, index);
}

bool customItemDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index)
{
    QMouseEvent* pEvent = static_cast<QMouseEvent*> (event);
    mousePos = pEvent->pos();
    //qDebug()<<event->type();
    if (ItemButton::withinButtonRegion(mousePos, option))
    {
        if(index.column()==m_CustomModel->m_btnColumn){
            switch (event->type())
            {
            case QEvent::MouseButtonPress:
                itemButton1->setStatusPressed();
                emit sizeHintChanged(index);
                emit sig_btnClicked(index);
                return false;
                break;
            case QEvent::MouseButtonRelease:
                itemButton1->setStatusReleased();
                emit sizeHintChanged(index);
                return true;
                break;
            default:
                return QStyledItemDelegate::editorEvent(event, model, option, index);
                break;
            }
        }
        return QStyledItemDelegate::editorEvent(event, model, option, index);
    }
    return QStyledItemDelegate::editorEvent(event, model, option, index);
}

void customItemDelegate::slots_btnClicked(const QModelIndex &index)
{

}



